package org.ezplatform.office.questionnaire.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.ezplatform.cloud.api.component.popuser.PopUserScopeUtilService;
import org.ezplatform.cloud.api.system.org.OrgApiService;
import org.ezplatform.component.permission.service.CmpApplyScopeService;
import org.ezplatform.core.dao.jpa.JpaBaseDao;
import org.ezplatform.core.service.BaseService;
import org.ezplatform.office.questionnaire.dao.QuestionnaireSetDao;
import org.ezplatform.office.questionnaire.dao.QuestionnaireSetTopicDao;
import org.ezplatform.office.questionnaire.dao.QusetionnaireAnswerStatusDao;
import org.ezplatform.office.questionnaire.entity.QuestionnaireSet;
import org.ezplatform.office.questionnaire.entity.QuestionnaireSetTopic;
import org.ezplatform.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service("QuestionnaireSetService")
@Transactional
public class QuestionnaireSetService extends BaseService<QuestionnaireSet,String>{
	
	private final static Logger LOGGER = LoggerFactory.getLogger(QuestionnaireSetService.class);
	
	@Autowired
	@Qualifier("questionnaireSetDao")
	private QuestionnaireSetDao questionnaireSetDao;
	
	@Autowired
	@Qualifier("questionnaireSetTopicDao")
	private QuestionnaireSetTopicDao  questionnaireSetTopicDao;
	
	@Autowired
	@Qualifier("qusetionnaireAnswerStatusDao")
	private QusetionnaireAnswerStatusDao answerStatusDao;
	
	@Autowired
	private PopUserScopeUtilService popScopeService;
	
	@Autowired
	private OrgApiService orgApiService;
	
	@Autowired
	private CmpApplyScopeService cmpApplyScopeService;

	@Override
	protected JpaBaseDao<QuestionnaireSet, String> getEntityDao() {
		return questionnaireSetDao;
	}
	
	/**
	 * 判断题库名称是否相同
	 * @param id 题库ID
	 * @param setName 题库名称
	 * @param corpId 单位ID
	 * @return 相同返回true、不同返回false
	 */
	public boolean checkName(String id,String setName,String corpId){
		boolean flag= false;
		QuestionnaireSet questionnaireSet = questionnaireSetDao.getQuestionnaireSetByName(setName,corpId);
		if(questionnaireSet !=null){
			if (StringUtils.isNotBlank(StringUtils.null2String(id))) {
				if(!id.equals(questionnaireSet.getId())){
					flag = true;
				}
			}else{
				flag = true;
			}
		}
		return flag;
	}
	
	/**
	 * 根据id查找题库信息
	 * @param id
	 * @return
	 */
	public Map<String,Object> getQuesSetInfoById(String id){
		Map<String, Object> paramMap = new HashMap<String, Object>();
		StringBuffer sql = new StringBuffer();
		sql.append(" SELECT t.id, t.set_type setType, t.set_name setName, t.set_scope setScope, t.status, t.description, t.sum_topic_num sumTopicNum FROM oa_questionnaire_set t WHERE t.ID = :id");
		paramMap.put("id", id);
		List<Map> list = super.findByListNativeQuery(sql.toString(), null,paramMap);
		if(CollectionUtils.isNotEmpty(list)){
			return list.get(0);
		}
		return new HashMap<String,Object>();
	}
	
	/**
	 * 根据问卷Id查找题库信息列表
	 * 
	 * @param quesitionnaireId
	 * @return List<Map>
	 */
	public List<Map> getQuesSetListByQuesId(String quesitionnaireId) {
		Map<String, Object> paramMap = new HashMap<String, Object>();
		StringBuffer sql = new StringBuffer();
		sql.append(
				" SELECT t.id, t.set_type setType, t.set_name setName, t.set_scope setScope, t.status, t.description, t.sum_topic_num sumTopicNum FROM oa_questionnaire_set t WHERE t.set_type = (SELECT m.type FROM oa_questionnaire m WHERE m.id = :quesitionnaireId) and t.status = 1");
		paramMap.put("quesitionnaireId", quesitionnaireId);
		List<Map> list = super.findByListNativeQuery(sql.toString(), null, paramMap);
		return list;
	}
	
	/**
	 * 
	 * @Title getQuSetTreeData
	 * @Description: 获取题库树JSON
	 * @param pageable
	 * @param searchTreeData
	 * @return
	 */
	public String getQuSetTreeData(String corpId, String setType, String setName, String userId, String token) {
		StringBuilder sql = new StringBuilder();
		sql.append(
				"SELECT t.ID, t.set_type, t.set_name FROM oa_questionnaire_set t WHERE t.status = 1 AND t.corp_id = :corpId");
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("corpId", corpId);
		if (StringUtils.isNotBlank(setType)) {
			sql.append(" AND t.set_type = :setType");
			paramMap.put("setType", setType);
		}
		if (StringUtils.isNotBlank(setName)) {
			sql.append(" AND t.set_name LIKE :setName");
			paramMap.put("setName", "%" + setName + "%");
		}
		String scopeSql = this.cmpApplyScopeService.getInScopeDataSql(userId, "oa_questionnaire_scope", "oa_questionnaire_set", "set_scope", "t", paramMap);
		List<String> scopelist = this.cmpApplyScopeService.getAllOrgStaGrpIdsByUserId(userId);
		paramMap.put("OrgStaGrpIds", scopelist);
		sql.append(" and " + scopeSql);
		List<Map> setList = super.findByListNativeQuery(sql.toString(), " order by t.createdDate desc", paramMap);
		StringBuilder str = new StringBuilder("");
		str.append("[");
		String id = "";
		String type = "";
		String name = "";
		Map setMap;
		for (int i = 0; i < setList.size(); i++) {
			setMap = setList.get(i);
			id = StringUtils.null2String(setMap.get("ID"));
			List<QuestionnaireSetTopic> questionnaireSetTopicList = this.questionnaireSetTopicDao.getTopicBySetId(id);
			List<String> topicTypeList = new ArrayList<String>();
			if (CollectionUtils.isNotEmpty(questionnaireSetTopicList)) {
				for (QuestionnaireSetTopic questionnaireSetTopic : questionnaireSetTopicList) {
					String topicType = questionnaireSetTopic.getTopicType();
					if (!topicTypeList.contains(topicType)) {
						topicTypeList.add(topicType);
					}
				}
			}
			type = StringUtils.null2String(setMap.get("set_type"));
			name = StringUtils.null2String(setMap.get("set_name"));
			String title = name;
			if (name.length() > 15) {
				name = name.substring(0, 15) + "...";
			}
			str.append("{\"setId\":\"" + id + "\",\"type\":\"" + type + "\",");
			str.append("\"name\":\"");
			str.append(name + "\",");
			str.append("\"title\":\"");
			str.append(title + "\",");
			str.append("\"open\":false,");
			str.append("\"children\":[");
			if ("questionnaireVote".equals(type)) {
				if (topicTypeList.contains("sinselect")) {
					str.append("{\"setId\":\""+id+"\",\"name\":\"投票单选\",\"title\":\"投票单选\",\"topicType\":\"sinselect\"},");
				}
				if (topicTypeList.contains("multiselect")) {
					str.append("{\"setId\":\""+id+"\",\"name\":\"投票多选\",\"title\":\"投票多选\",\"topicType\":\"multiselect\"},");
				}
				String voteResultStr = str.toString();
				if (voteResultStr.endsWith(",")) {
					voteResultStr = voteResultStr.substring(0, voteResultStr.length() - 1);
				}
				str = new StringBuilder(voteResultStr);
			}
			if ("questionnaireSurvey".equals(type)) {
				if (topicTypeList.contains("sinselect")) {
					str.append("{\"setId\":\""+id+"\",\"name\":\"普通单选\",\"title\":\"普通单选\",\"topicType\":\"sinselect\"},");
				}
				if (topicTypeList.contains("multiselect")) {
					str.append("{\"setId\":\""+id+"\",\"name\":\"普通多选\",\"title\":\"普通多选\",\"topicType\":\"multiselect\"},");
				}
				if (topicTypeList.contains("check")) {
					str.append("{\"setId\":\""+id+"\",\"name\":\"下拉框\",\"title\":\"下拉框\",\"topicType\":\"check\"},");
				}
				if (topicTypeList.contains("field")) {
					str.append("{\"setId\":\""+id+"\",\"name\":\"上传附件\",\"title\":\"上传附件\",\"topicType\":\"field\"},");
				}
				if (topicTypeList.contains("answer")) {
					str.append("{\"setId\":\""+id+"\",\"name\":\"单项填空\",\"title\":\"单项填空\",\"topicType\":\"answer\"},");
				}
				if (topicTypeList.contains("fillInBlanks")) {
					str.append("{\"setId\":\""+id+"\",\"name\":\"多项填空\",\"title\":\"多项填空\",\"topicType\":\"fillInBlanks\"},");
				}
				if (topicTypeList.contains("scale")) {
					str.append("{\"setId\":\""+id+"\",\"name\":\"量表\",\"title\":\"量表\",\"topicType\":\"scale\"},");
				}
				if (topicTypeList.contains("mulscale")) {
					str.append("{\"setId\":\""+id+"\",\"name\":\"矩阵量表\",\"title\":\"矩阵量表\",\"topicType\":\"mulscale\"},");
				}
				String surveyResultStr = str.toString();
				if (surveyResultStr.endsWith(",")) {
					surveyResultStr = surveyResultStr.substring(0, surveyResultStr.length() - 1);
				}
				str = new StringBuilder(surveyResultStr);
			}
			if ("questionnaireExam".equals(type)) {
				if (topicTypeList.contains("sinselect")) {
					str.append("{\"setId\":\""+id+"\",\"name\":\"考试单选\",\"title\":\"考试单选\",\"topicType\":\"sinselect\"},");
				}
				if (topicTypeList.contains("multiselect")) {
					str.append("{\"setId\":\""+id+"\",\"name\":\"考试多选\",\"title\":\"考试多选\",\"topicType\":\"multiselect\"},");
				}
				if (topicTypeList.contains("trueOrFalse")) {
					str.append("{\"setId\":\""+id+"\",\"name\":\"考试判断\",\"title\":\"考试判断\",\"topicType\":\"trueOrFalse\"},");
				}
				if (topicTypeList.contains("answer")) {
					str.append("{\"setId\":\""+id+"\",\"name\":\"单项填空\",\"title\":\"单项填空\",\"topicType\":\"answer\"},");
				}
				if (topicTypeList.contains("fillInBlanks")) {
					str.append("{\"setId\":\""+id+"\",\"name\":\"多项填空\",\"title\":\"多项填空\",\"topicType\":\"fillInBlanks\"},");
				}
				if (topicTypeList.contains("shortAnswer")) {
					str.append("{\"setId\":\""+id+"\",\"name\":\"考试简答\",\"title\":\"考试简答\",\"topicType\":\"shortAnswer\"},");
				}
				if (topicTypeList.contains("field")) {
					str.append("{\"setId\":\""+id+"\",\"name\":\"考试文件\",\"title\":\"考试文件\",\"topicType\":\"field\"},");
				}
				String examResultStr = str.toString();
				if (examResultStr.endsWith(",")) {
					examResultStr = examResultStr.substring(0, examResultStr.length() - 1);
				}
				str = new StringBuilder(examResultStr);
			}
			str.append("]},");
		}
		String resultStr = str.toString();
		if (resultStr.endsWith(",")) {
			resultStr = resultStr.substring(0, resultStr.length() - 1);
		}
		resultStr += "]";
		return resultStr;
	}
	
}
